package main

import (
	"fmt"
	"runtime"
	"time"
	"ysnet/tcp"
)

type Callback struct {
	recvByte int
	isClient bool
}

func (cb *Callback) OnConnect(c *tcp.Conn) error {
	if cb.isClient {
		c.Send([]byte("hello world"), 0)
	} else {
		fmt.Println("Client connected:", c.GetSocket().RemoteAddr())
	}
	return nil
}

func (cb *Callback) OnMessage(c *tcp.Conn, buff []byte) error {
	cb.recvByte += len(buff)
	c.Send([]byte("hello world"), 0)
	if cb.isClient {
		//fmt.Println(">>>", string(buff))
	} else {
		//fmt.Println("<<<", string(buff))
		//c.Close()
	}
	return nil
}

func (cb *Callback) OnClose(c *tcp.Conn) {
	if cb.isClient {
		fmt.Println("client recv bytes:", cb.recvByte)
	} else {
		fmt.Println("server recv bytes:", cb.recvByte)
		fmt.Println("conn closed ", c.GetSocket().RemoteAddr())
	}
}

func (cb *Callback) OnError(c *tcp.Conn, err error) {
	//fmt.Println("handle err:", err)
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	s := tcp.NewServer(&Callback{isClient: false, recvByte: 0}, &tcp.ServerConfig{
		ListenAddr:  ":8989",
		SendChanMax: 1024,
		RecvChanMax: 1024,
	})

	s.Start()

	cl := tcp.NewClient(&Callback{isClient: true, recvByte: 0}, &tcp.ClientConfig{
		Host:        "127.0.0.1:8989",
		SendChanMax: 1024,
		RecvChanMax: 1024,
	})

	cl.Start()
	/*
		go func() {
			for {
				if cl.IsClosed() {
					cl.Close()
					cl = tcp.NewClient(&Callback{isClient: true, recvByte: 0}, &tcp.ClientConfig{
						Host:        "127.0.0.1:8989",
						SendChanMax: 1024,
						RecvChanMax: 1024,
					})
					cl.Start()
				}
			}
		}()
	*/

	/*
		chSig := make(chan os.Signal)
		signal.Notify(chSig, syscall.SIGINT, syscall.SIGTERM)
		fmt.Println("Signal: ", <-chSig)
	*/

	select {
	case <-time.After(60 * time.Second):
		break
	}

	cl.Close()
	s.Close()
}
